﻿using System;
using System.Collections.Generic;
using System.Text;

using Gx.Model.Entity;//实体
using Gx.Common;//通用类
using Gx.Model;
using Gx.Dal.Employee;
using Gx.Model.Enums;
using Gx.Bll.Shared;
using System.Linq;

namespace Gx.Bll.Employee
{
    /// <summary>
    /// 出库
    /// </summary>
    public class G_StockOutInfoBll
    {
        /// <summary>
        /// 添加一条出库单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnModel<bool> AddG_StockOutInfo(string data)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                if (string.IsNullOrEmpty(data))
                {
                    r.Msg = "参数错误";
                    return r;
                }
                G_StockOutInfo model = JsonHelper.DeserializeObject<G_StockOutInfo>(data);
                if (model.GoodsList == null && model.GoodsList.Count == 0)
                {
                    r.Msg = "请选择物料";
                    return r;
                }
                if (model.GoodsList.Exists(x => x.Num <= 0))
                {
                    r.Msg = "出库数量必须都大于0";
                    return r;
                }
                if (model.CheckUser < 0)
                {
                    r.Msg = "请选择复核人";
                    return r;
                }
                if (model.GoodsList.GroupBy(x => x.GoodsId).Any(x => x.Count() > 1))
                {
                    r.Msg = "物料不能重复";
                    return r;
                }
                r.Msg = "";
                List<int> goodsIdList = model.GoodsList.Select(x => x.GoodsId).ToList();
                List<G_GoodsInfo> goodsList = new G_GoodsInfoBll().GetG_GoodsInfoList(goodsIdList);
                bool noNum = false;
                List<G_StocksTotalInfo> stList = new G_StocksTotalInfoBll().GetG_StocksTotalInfoList(goodsIdList);
                foreach (var item in goodsList)
                {
                    decimal needNumTotal = model.GoodsList.Where(x => x.GoodsId == item.GoodsId).Sum(x => x.Num);
                    if (stList.Exists(x => x.Num < needNumTotal))
                    {
                        r.Msg += string.Format("商品:{0}", item.GoodsName);
                        noNum = true;
                    }
                }
                if (noNum)
                {
                    r.Msg = string.Format("如下物料超过库存:{0}", r.Msg);
                    return r;
                }
                model.AddTime = model.LastEditTime = DateTime.Now;
                model.EmployeeId = model.AddUser = model.LastEditUser = LoginHelper.GetUserId();
                model.CheckStatus = (int)CheckStatus.审批中;
                model.BillStatus = (int)BillStatus.正常;
                model.BillNo = DateTime.Now.ToStringyyyyMMddHHmmfff("CK");
                model.GoodsId = goodsIdList.Join();
                model.GoodsName = string.Join(",", goodsList.Select(x => x.GoodsName));

                int StockOutId = dal.AddG_StockOutInfo(model);
                if (StockOutId > 0)
                {
                    new M_LogInfoBll().AddOptionsLog("AddG_StockOutInfo", "添加一条出库信息", data);
                    G_StockOutGoodsInfoBll goodsBll = new G_StockOutGoodsInfoBll();
                    foreach (var item in model.GoodsList)
                    {
                        G_GoodsInfo goods = goodsList.Find(x => x.GoodsId == item.GoodsId);
                        item.GoodsName = goods.GoodsName;
                        item.StockOutId = StockOutId;
                        item.UnitValue = goods.UnitValue;
                        if (item.Num > 0)
                        {
                            item.Num *= -1;
                        }
                        goodsBll.AddG_StockOutGoodsInfo(item);
                    }
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }

        public ReturnModel<bool> DelG_StockOutInfo(int stockOutId)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                G_StockOutInfo model = new G_StockOutInfo
                {
                    LastEditTime = DateTime.Now,
                    LastEditUser = LoginHelper.GetUserId(),
                    Status = 1,
                    StockOutId = stockOutId,
                };
                bool res = dal.DelG_StockOutInfo(model);
                if (res)
                {
                    new M_LogInfoBll().AddOptionsLog("DelG_StockOutInfo", "作废一条出库信息", model);
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }

        /// <summary>
        ///作废一条入库信息
        /// </summary>
        /// <param name="purchaseOrderId"></param>
        /// <returns></returns>
        public ReturnModel<bool> DelG_StockOutInfo_BillStatus(int StockOutId)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                G_StockOutInfo model = new G_StockOutInfo
                {
                    LastEditTime = DateTime.Now,
                    LastEditUser = LoginHelper.GetUserId(),
                    BillStatus = (int)BillStatus.作废,
                    StockOutId = StockOutId,
                };
                bool res = dal.DelG_StockOutInfo_BillStatus(model);
                if (res)
                {
                    new M_LogInfoBll().AddOptionsLog("DelG_StockOutInfo_BillStatus", "作废一条出库单信息", model);
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }


        public ReturnModel<bool> EditG_StockOutInfo_CheckUser(G_StockOutInfo model)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                ReturnModel<bool> r = new ReturnModel<bool>()
                {
                    Code = (int)Code.操作失败,
                    Msg = "操作失败",
                    Success = false,
                };
                model.LastEditUser = LoginHelper.GetUserId();
                model.CheckDate = model.LastEditTime = DateTime.Now;
                bool res = dal.EditG_StockOutInfo_CheckUser(model);
                if (!res)
                {
                    return r;
                }
                new M_LogInfoBll().AddOptionsLog("EditG_StockOutInfo_CheckUser", "审核一条出库单", model);
                if (model.CheckStatus == (int)CheckStatus.审批通过)
                {
                    List<G_StockOutGoodsInfo> sogList = new G_StockOutGoodsInfoBll().GetG_StockOutGoodsInfoList(model.StockOutId);
                    G_StocksInfoBll siBll = new G_StocksInfoBll();
                    G_StocksTotalInfoBll stBll = new G_StocksTotalInfoBll();
                    foreach (var item in sogList)
                    {
                        siBll.AddG_StocksInfo(new G_StocksInfo()
                        {
                            Num = item.Num,
                            GoodsId = item.GoodsId,
                            ObjectId = item.StockOutId
                        });
                        stBll.EditG_StocksTotalInfo(new G_StocksTotalInfo()
                        {
                            GoodsId = item.GoodsId,
                            Num = item.Num
                        });
                    }
                    r.Code = (int)Code.操作成功;
                    r.Msg = "操作成功";
                    r.Data = true;
                    r.Success = true;
                }
                return r;
            }
        }


        private List<G_StockOutInfo> GetG_StockOutInfoList(string strWhere)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                return dal.GetG_StockOutInfoList(strWhere);
            }
        }

        public List<G_StockOutInfo> GetG_StockOutInfoList(string BillNo, int? CheckStatus, DateTime? StartCheckDate, DateTime? EndCheckDate,
            int? BillStatus,
int pageIndex, int pageSize, out int totalCount)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                int PageIndex = (pageIndex - 1) * pageSize + 1;
                int PageSize = pageIndex * pageSize;
                StringBuilder strWhere = new StringBuilder();
                if (!BillStatus.IsNull() && BillStatus > -1)
                {
                    strWhere.AppendFormat("   AND BillStatus={0}", BillStatus);
                }
                if (!CheckStatus.IsNull() && CheckStatus > -1)
                {
                    strWhere.AppendFormat("   AND CheckStatus={0}", CheckStatus);
                }
                if (!BillNo.IsNullOrEmpty())
                {
                    strWhere.AppendFormat(" AND BillNo LIKE '%{0}%'", BillNo);
                }
                if (StartCheckDate.IsDate())
                {
                    strWhere.AppendFormat(" AND CheckDate>='{0}'", StartCheckDate);
                }
                if (EndCheckDate.IsDate())
                {
                    strWhere.AppendFormat(" AND CheckDate <= '{0}' ", EndCheckDate);
                }
                List<G_StockOutInfo> list = dal.GetG_StockOutInfoList(strWhere.ToString(), PageIndex, PageSize, out totalCount);
                foreach (var item in list)
                {
                    item.StrBillStatus = EnumHelper.GetDataTypeDescription<BillStatus>(item.BillStatus);
                    item.StrAddTime = item.AddTime.ToStringyyyyMMdd();
                    item.StrCheckStatus = EnumHelper.GetDataTypeDescription<CheckStatus>(item.CheckStatus);
                }

                return list;
            }
        }

        private int GetG_StockOutInfoCount(string strWhere)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                return dal.GetG_StockOutInfoCount(strWhere);
            }
        }

        public G_StockOutInfo GetG_StockOutInfoModel(int stockOutId, bool isGetEmployee = false)
        {
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                G_StockOutInfo so = dal.GetG_StockOutInfoModel(stockOutId);
                if (isGetEmployee)
                {
                    List<int> empIdList = new List<int>() { so.CheckUser, so.EmployeeId };
                    List<E_EmployeeInfo> empList = new E_EmployeeInfoBll().GetE_EmployeeInfoList(empIdList);
                    so.EmpName = empList.Exists(x => x.EmployeeId == so.EmployeeId) ? empList.Find(x => x.EmployeeId == so.EmployeeId).EmpName : "员工不存在或已离职";
                    so.CheckUserName = empList.Exists(x => x.EmployeeId == so.CheckUser) ? empList.Find(x => x.EmployeeId == so.CheckUser).EmpName : "员工不存在或已离职";
                }
                return so;
            }
        }

        public List<G_StockOutInfo> GetG_StockOutInfoLikeFront10(string billNo)
        {
            if (billNo.IsNullOrEmpty() || billNo.Length < 2)
            {
                return new List<G_StockOutInfo>();
            }
            using (G_StockOutInfoDal dal = new G_StockOutInfoDal())
            {
                return dal.GetG_StockOutInfoLikeFront10(billNo);
            }
        }
    }
}
